Each
task is a sequential operation; however, tasks can often run in
parallel. In .NET, a task is also an object with properties and methods
of its own. Here’s some sequential code.
DoLeft();
DoRight();
Let’s assume that the methods DoLeft and DoRight
are independent. This means that neither method writes to memory
locations or files that the other method might read. Because the
methods are independent, you can use the Invoke method of the Parallel class to call them in parallel. This is shown in the following code.
Parallel.Invoke(DoLeft, DoRight);
Parallel.Invoke is the simplest expression of the parallel task pattern. It creates new parallel tasks for each delegate method that is in its params array argument list. The Invoke method returns when all the tasks are finished.
Note:
Parallel.Invoke is a method in .NET that creates a list of parallel tasks and waits for them all to complete.
You can’t assume that
all parallel tasks will immediately run. Depending on the current work
load and system configuration, tasks might be scheduled to run one
after another, or they might run at the same time.
The delegate methods of Parallel.Invoke can either complete normally or finish by throwing an exception. Any exceptions that occur during the execution of Parallel.Invoke are deferred and rethrown when all tasks finish. All exceptions are rethrown as inner exceptions of an AggregateException instance.
Note:
Two tasks, t1 and t2, are needed in this example for correct exception handling. Without the second task, t2, the code would not have guaranteed that exceptions thrown during the execution of task t1 would be observed.
Internally, Parallel.Invoke creates new tasks and waits for them. It uses methods of the Task class to do this. Here’s an example.
Task t1 = Task.Factory.StartNew(DoLeft);
Task t2 = Task.Factory.StartNew(DoRight);
Task.WaitAll(t1, t2);
The StartNew method of the TaskFactory class creates and schedules a new task that executes the delegate method that is provided as its argument. You can wait for parallel tasks to complete by calling the Task.WaitAll method. (Use the Wait method if you want to wait on a single task.)
Note:
Use the StartNew factory method to create a task and schedule it to run. Use Task.WaitAll to wait for more than one task to complete before proceeding.
When you use StartNew
to create a task, the new task is added to a work queue for eventual
execution, but it does not start to run until its task scheduler takes
it out of the work queue, which can happen immediately or can occur at
some point in the future.
The examples you’ve seen so far
are simple, but they’re powerful enough to handle many scenarios.